package com.spring.security.handler;

import com.spring.security.model.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * @author HouKunLin
 */
@RestControllerAdvice
@Slf4j
public class MyExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public JsonResult exception(Exception e) {
        log.debug("严重错误", e);
        return JsonResult.error(HttpStatus.INTERNAL_SERVER_ERROR, e);
    }

    @ExceptionHandler({NoHandlerFoundException.class})
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public JsonResult noHandlerFoundException(NoHandlerFoundException e) {
        return JsonResult.error(HttpStatus.NOT_FOUND, e)
                .data()
                .put("requestURL", e.getRequestURL())
                .put("httpMethod", e.getHttpMethod())
                .result();
    }

    @ExceptionHandler(AuthenticationException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public JsonResult authenticationException(AuthenticationException e) {
        return JsonResult.error(HttpStatus.UNAUTHORIZED, e);
    }
}
